package com.honeywell.iotserver.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.honeywell.iotserver.entity.Camera;
import com.honeywell.iotserver.entity.DeviceResponseEntity;
import com.honeywell.iotserver.entity.MyUUID;
import com.honeywell.iotserver.repository.DeviceRepository;
import com.honeywell.iotserver.repository.DevicesDynamicQueryRepository;
import com.honeywell.iotserver.repository.RandomGeneRepository;
import com.honeywell.iotserver.repository.UUIDRepository;
import com.honeywell.iotserver.utils.AliClient;
import com.honeywell.iotserver.utils.MyProps;

@RestController
@RequestMapping
public class DeviceController {
	private static Logger logger = LoggerFactory
			.getLogger(DeviceController.class);
	@Autowired
	private DeviceRepository deviceRepository;
	@Autowired
	private UUIDRepository uuidRepository;
	@Autowired
	private DevicesDynamicQueryRepository devicesDynamicQueryRepository;
	@Autowired
	private MyProps myProps;


	/**
	 * 获取设备列表
	 * 
	 * @param configState
	 * @param type
	 * @param search
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/device", method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceList(
			@RequestParam(value = "configState", required = false) List<Integer> configState,
			@RequestParam(value = "type", required = false) List<String> type,
			@RequestParam(value = "search", required = false) String search,
			@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
		logger.info("{CONFIGSTATE=" + configState + ",TYPE=" + type
				+ ",SEARCH=" + search + ",PAGE=" + page + ",PAGESIZE="
				+ pageSize + "}");
		StringBuilder selectSQLCondition = new StringBuilder();
		StringBuilder countSQLCondition = new StringBuilder();
		StringBuilder whereSQLCondition = new StringBuilder(
				" where is_del = 0 ");
		selectSQLCondition
				.append("select id,uuid,config_status,rtmp_url,mac_address,status,type from t_camera ");
		countSQLCondition
				.append(" select count(1) from t_camera ");
		if (configState != null && configState.size() > 0) {
			whereSQLCondition.append(" and config_status in " + configState);
		}
		if (type != null && type.size() > 0) {
			// 把[camera]转换为['camera']加单引号
			whereSQLCondition.append(" and type in "
					+ type.stream().map((data) -> "'" + data + "'")
							.collect(Collectors.toList()));
		}
		if (!StringUtils.isBlank(search)) {
			whereSQLCondition.append(" and (rtmp_url like " + "'%" + search
					+ "%'" + " or mac_address like " + "'%" + search + "%'"
					+ " or uuid like " + "'%" + search + "%'" + ")");

		}

		selectSQLCondition.append(whereSQLCondition.toString());
		countSQLCondition.append(whereSQLCondition.toString());

		selectSQLCondition.append(" limit " + ((page - 1) * pageSize) + ","
				+ pageSize);
		String executeSQL = selectSQLCondition.toString()
				.replaceAll("\\[", "(").replaceAll("\\]", ")");
		String countSQL = countSQLCondition.toString().replaceAll("\\[", "(")
				.replaceAll("\\]", ")");
		List<Object> list = devicesDynamicQueryRepository
				.findDeviceLists(executeSQL);
		int pageTotal = devicesDynamicQueryRepository.deviceCount(countSQL);
		List<DeviceResponseEntity> deviceList = new ArrayList<DeviceResponseEntity>();
		if (list != null && list.size() > 0) {
			for (Object camera : list) {
				Object[] objects = (Object[]) camera;
				DeviceResponseEntity deviceResponseEntity = new DeviceResponseEntity();
				deviceResponseEntity.setId((int) objects[0]);
				deviceResponseEntity.setUuid(objects[1] + "");
				deviceResponseEntity.setConfigState(objects[2] + "");
				deviceResponseEntity.setIp(objects[3] + "");
				deviceResponseEntity.setMacAddr(objects[4] + "");
				deviceResponseEntity.setStatus(objects[5] + "");
				deviceResponseEntity.setType(objects[6] + "");
				deviceList.add(deviceResponseEntity);
			}
		}
		// 封装返回结果为一个map对象
		Map<String, Object> resultMap = new HashMap<>();
		// 列表信息
		resultMap.put("pageInfos", deviceList);
		// 总条数
		resultMap.put("total", pageTotal);
		// 当前页数
		resultMap.put("curPage", page);
		// 每页的大小
		resultMap.put("pageSize", pageSize);
		return JSON.toJSONString(resultMap);

	}

	/**
	 * 删除指定id设备
	 * 
	 * @param id
	 * @return
	 */

	@RequestMapping(value = "/device/{uuid}", method = RequestMethod.DELETE)
	public void deleteDeviceByUUID(
			@PathVariable(value = "uuid", required = true) String uuid,
			HttpServletResponse response) {

		logger.info("{UUID=" + uuid + ",HTTPSERVLETRESPONSE=" + response + "}");
		try {
			Integer result = deviceRepository.deleteDevice(uuid);
			Map<String, String> map = new HashMap<>();
			Integer code = HttpServletResponse.SC_OK;
			String message = "successful operation";
			map.put("code", code.toString());
			map.put("message", message);

			if (result == null || result <= 0) {
				map.put("code", new Integer(HttpServletResponse.SC_BAD_REQUEST)
						.toString());
				map.put("message", "Invalid ID supplied");
			}
			response.getWriter().println(JSON.toJSONString(map));
			AliClient.sendPostDataByJson(myProps.getAilurl(), uuid, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 配置指定设备
	 * 
	 * @param uuid
	 * @param configstate
	 * @return
	 */
	@RequestMapping(value = "/device/{uuid}/configState", method = RequestMethod.PUT)
	@ResponseBody
	public String editDeviceConfigstate(
			@PathVariable(value = "uuid", required = true) String uuid,
			@RequestParam(value = "configState", required = true) Integer configState) {

		logger.info("{UUID=" + uuid + ",CONFIGSTATE=" + configState + "}");
		deviceRepository.updateConfigState(uuid, configState);
		Map<String, String> map = new HashMap<>();
		map.put("code", new Integer(HttpServletResponse.SC_OK).toString());
		map.put("message", "successful operation");
		return JSON.toJSONString(map);

	}

	/**
	 * 注册接口
	 */
	@RequestMapping(value = "/create/{size}", method = RequestMethod.PUT)
	public String createUUID(
			@PathVariable(value = "size", required = true) Integer size) {

		logger.info("{SIZE=" + size + "}");

		// 生成相应数量的uuid并存入数据库
		if (size == null)
			return String.valueOf(HttpServletResponse.SC_BAD_REQUEST);
		List<MyUUID> list = new ArrayList<MyUUID>();
		List<Camera> list2 = new ArrayList<Camera>();
		RandomGeneRepository account = new RandomGeneRepository();
		RandomGeneRepository password = new RandomGeneRepository();
		RandomGeneRepository secret_key = new RandomGeneRepository();
		for (int i = 0; i < size; i++) {
			MyUUID myUUID = new MyUUID();
			String key = secret_key.RandomGeneration(1024, false, false, true);
			Date date = new Date();
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			myUUID.setUuid(uuid);
			myUUID.setGenerate_time(date);
			myUUID.setAccount(account.RandomGeneration(6, true, true, true));
			myUUID.setPassword(password.RandomGeneration(6, true, true, true));
			myUUID.setSecret_key(key);
			myUUID.setKey_id(1);
			list.add(myUUID);

			Camera camera = new Camera();
			camera.setBrand("1");
			camera.setConfig_status(0);
			camera.setIs_del(0);
			camera.setMac_address("WW-00-RR-22-TT-11");
			camera.setMode("1");
			camera.setProduct_time(date);
			camera.setRtmp_url("192.168.0.100");
			camera.setSerial("1");
			camera.setStatus(0);
			camera.setOpened(0);
			camera.setType("camera");
			camera.setUuid(uuid);
			list2.add(camera);
		}
		uuidRepository.saveAll(list);
		deviceRepository.saveAll(list2);

		// 以JSON返回
		return JSON.toJSONString(list);
	}

}
